/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.minierp.dao.EstPriceDao;
import com.minierp.dao.IdGenerator;
import com.minierp.dao.MakeTypeDao;
import com.minierp.dao.ProductDao;
import com.minierp.err.PermissionDennyException;
import com.minierp.helper.EncCommonHelper;
import com.minierp.helper.PageHelper;
import com.minierp.model.EstPrice;
import com.minierp.model.Establishment;
import com.minierp.model.MakeType;
import com.minierp.model.Product;
import com.minierp.view.EstPriceListExcelView;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class EstPriceMACtr extends MultiActionController {
	private EstPriceDao estPriceDao;
	private MakeTypeDao makeTypeDao;
	private ProductDao productDao;
	private IdGenerator idGenerator;
	private String listView;
	private String listForEstView;
	private String listForSelectView;
	private String listForMultiSelectView;
	private String impoFormView;

	public String getListForMultiSelectView() {
		return this.listForMultiSelectView;
	}

	public void setListForMultiSelectView(String listForMultiSelectView) {
		this.listForMultiSelectView = listForMultiSelectView;
	}

	public IdGenerator getIdGenerator() {
		return this.idGenerator;
	}

	public void setIdGenerator(IdGenerator idGenerator) {
		this.idGenerator = idGenerator;
	}

	public ProductDao getProductDao() {
		return this.productDao;
	}

	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}

	public String getImpoFormView() {
		return this.impoFormView;
	}

	public void setImpoFormView(String impoFormView) {
		this.impoFormView = impoFormView;
	}

	public String getListForEstView() {
		return this.listForEstView;
	}

	public void setListForEstView(String listForEstView) {
		this.listForEstView = listForEstView;
	}

	public ModelAndView handleList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView(this.listView);
		String proName = request.getParameter("pro_name");
		String priceType = request.getParameter("price_type");
		String estType = request.getParameter("est_type");
		String estName = request.getParameter("est_name");
		String estId = request.getParameter("est_id");
		String mtId = request.getParameter("mt_id");
		if (estType != null && estType.equals("COOPERATOR")) {
			if (!EncCommonHelper.checkPrivilege(request, "COOP_PRIC")) {
				throw new PermissionDennyException("Permission Denny");
			}
		} else if (estType != null && estType.equals("CLIENT")) {
			if (!EncCommonHelper.checkPrivilege(request, "CLIE_PRIC")) {
				throw new PermissionDennyException("Permission Denny");
			}
		} else if (estType != null && estType.equals("PROVIDER")
				&& !EncCommonHelper.checkPrivilege(request, "PROV_PRIC")) {
			throw new PermissionDennyException("Permission Denny");
		}

		if (mtId == null || mtId.equals("")) {
			mtId = "0";
		}

		if (estId == null || estId.equals("")) {
			estId = "0";
		}

		if (priceType == null || priceType.equals("")) {
			priceType = "STA";
		}

		int total = this.estPriceDao
				.getListCount(estType, Long.parseLong(mtId), priceType,
						proName, Long.parseLong(estId));
		String contentType = request.getParameter("content_type");
		if (contentType != null && contentType.equals("EXCEL")) {
			HashMap perPageNum1 = new HashMap();
			List pageno1 = this.estPriceDao.getList(estType,
					Long.parseLong(mtId), priceType, proName,
					Long.parseLong(estId), 0, total);
			perPageNum1.put("list", pageno1);
			EstPriceListExcelView startIndex1 = new EstPriceListExcelView();
			return new ModelAndView(startIndex1, perPageNum1);
		} else {
			int perPageNum = EncCommonHelper.getPageSize(request);
			int pageno = EncCommonHelper.getCurrentPageIndex(request, total,
					perPageNum);
			int startIndex = (pageno - 1) * perPageNum;
			List list = this.estPriceDao.getList(estType, Long.parseLong(mtId),
					priceType, proName, Long.parseLong(estId), startIndex,
					perPageNum);
			mv.addObject("mtList", this.makeTypeDao.getList(true));
			mv.addObject("qr", EncCommonHelper.parseQueryResult(list, total,
					perPageNum, pageno));
			mv.addObject("proName", proName);
			mv.addObject("estName", estName);
			mv.addObject("estId", estId);
			mv.addObject("mtId", mtId);
			mv.addObject("estType", estType);
			mv.addObject("priceType", priceType);
			return mv;
		}
	}

	public ModelAndView handleListForEst(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView(this.listForEstView);
		String proName = request.getParameter("pro_name");
		String estType = request.getParameter("est_type");
		String estId = request.getParameter("est_id");
		String mtId = request.getParameter("mt_id");
		if (mtId == null || mtId.equals("")) {
			mtId = "0";
		}

		int perPageNum = EncCommonHelper.getPageSize(request);
		int total = this.estPriceDao.getListCount(estType,
				Long.parseLong(mtId), "EST", proName, Long.parseLong(estId));
		int pageno = EncCommonHelper.getCurrentPageIndex(request, total,
				perPageNum);
		int startIndex = (pageno - 1) * perPageNum;
		List list = this.estPriceDao.getList(estType, Long.parseLong(mtId),
				"EST", proName, Long.parseLong(estId), startIndex, perPageNum);
		mv.addObject("qr", EncCommonHelper.parseQueryResult(list, total,
				perPageNum, pageno));
		mv.addObject("est", this.estPriceDao.get(Establishment.class,
				Long.parseLong(estId)));
		mv.addObject("mtList", this.makeTypeDao.getList(true));
		mv.addObject("proName", proName);
		mv.addObject("estId", estId);
		mv.addObject("mtId", mtId);
		mv.addObject("estType", estType);
		return mv;
	}

	public ModelAndView handleListForSelect(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String proName = request.getParameter("pro_name");
		String priceType = request.getParameter("price_type");
		String estType = request.getParameter("est_type");
		String estId = request.getParameter("est_id");
		String mtId = request.getParameter("mt_id");
		String unitRang = request.getParameter("unit_rang");
		String type = request.getParameter("type");
		ModelAndView mv = new ModelAndView(this.listForSelectView);
		if (type != null && type.equals("MULTI")) {
			mv = new ModelAndView(this.listForMultiSelectView);
		}

		if (mtId == null || mtId.equals("")) {
			mtId = "0";
		}

		if (estId == null || estId.equals("")) {
			estId = "0";
		}

		int perPageNum = EncCommonHelper.getPageSize(request);
		int total = this.estPriceDao.getListForSelectCount(estType,
				Long.parseLong(mtId), priceType, proName,
				Long.parseLong(estId), unitRang);
		int pageno = EncCommonHelper.getCurrentPageIndex(request, total,
				perPageNum);
		int startIndex = (pageno - 1) * perPageNum;
		List list = this.estPriceDao.getListForSelect(estType,
				Long.parseLong(mtId), priceType, proName,
				Long.parseLong(estId), unitRang, startIndex, perPageNum);
		mv.addObject("qr", EncCommonHelper.parseQueryResult(list, total,
				perPageNum, pageno));
		mv.addObject("est", this.estPriceDao.get(Establishment.class,
				Long.parseLong(estId)));
		mv.addObject("mtList", this.makeTypeDao.getList(true));
		mv.addObject("proName", proName);
		mv.addObject("estId", estId);
		mv.addObject("mtId", mtId);
		mv.addObject("estType", estType);
		mv.addObject("priceType", priceType);
		mv.addObject("unitRang", unitRang);
		mv.addObject("type", type);
		return mv;
	}

	public ModelAndView handleDelete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String estType = request.getParameter("est_type");
		String priCode = "";
		if (estType != null && estType.equals("CLIENT")) {
			priCode = "CLIE_PRIC";
		} else if (estType != null && estType.equals("PROVIDER")) {
			priCode = "PROV_PRIC";
		} else if (estType != null && estType.equals("COOPERATOR")) {
			priCode = "COOP_PRIC";
		}

		if (priCode.equals("")) {
			throw new Exception("Est type not supported!");
		} else if (EncCommonHelper.checkPrivilege(request, priCode)
				&& !EncCommonHelper.checkPurePrivilege(request, "NO_PRIC_EDIT")) {
			String retUrl = request.getParameter("from_url");
			ModelAndView mv = new ModelAndView("redirect:" + retUrl);
			String[] arr = request.getParameter("id").split(";");

			for (int i = 0; i < arr.length; ++i) {
				this.estPriceDao.delete(Long.parseLong(arr[i]));
			}

			EncCommonHelper.setAlertMessage(request, "删除成功！");
			return mv;
		} else {
			throw new Exception("Permission deny!");
		}
	}

	public ModelAndView handleGetListForEst(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HashMap map = new HashMap();

		try {
			String mapper = request.getParameter("est_id");
			List json = this.estPriceDao.getList(Long.parseLong(mapper));
			ArrayList out = new ArrayList();

			for (int i = 0; i < json.size(); ++i) {
				HashMap item = new HashMap();
				Object[] objs = (Object[]) json.get(i);
				String proName = (String) objs[1];
				if (proName == null) {
					proName = "";
				}

				item.put("mtId", objs[0].toString());
				item.put("proName", proName);
				item.put("price", objs[2].toString());
				out.add(item);
			}

			map.put("items", out);
			map.put("status", "OK");
			map.put("errMsg", "");
		} catch (Exception arg10) {
			map.put("status", "ERROR");
			map.put("errMsg", arg10.toString());
		}

		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		ObjectMapper arg11 = new ObjectMapper();
		String arg12 = arg11.writeValueAsString(map);
		ServletOutputStream arg13 = response.getOutputStream();
		arg13.write(arg12.getBytes("utf-8"));
		arg13.flush();
		arg13.close();
		return null;
	}

	public ModelAndView handleGetList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String estType = request.getParameter("est_type");
		String priceType = request.getParameter("price_type");
		List list;
		String mtList;
		if (priceType.equals("EST")) {
			mtList = request.getParameter("est_id");
			list = this.estPriceDao.getList(estType, priceType,
					Long.parseLong(mtList));
		} else {
			mtList = request.getParameter("mt_id");
			list = this.estPriceDao.getList(estType, priceType,
					mtList.split(";"));
		}

		List arg19 = this.makeTypeDao.getList(false);
		HashMap map = new HashMap();

		try {
			ArrayList mapper = new ArrayList();

			for (int json = 0; json < list.size(); ++json) {
				HashMap out = new HashMap();
				Object[] objs = (Object[]) list.get(json);
				String proName = "";
				String requ = "";
				String unit = "";
				String mark = "";
				String leng = "";
				String widt = "";
				String spec = "";
				if (objs[1] != null) {
					proName = (String) objs[1];
				}

				if (objs[2] != null) {
					requ = (String) objs[2];
				}

				if (objs[3] != null) {
					unit = (String) objs[3];
				}

				if (objs[5] != null) {
					mark = (String) objs[5];
				}

				if (objs[6] != null) {
					leng = (String) objs[6];
				}

				if (objs[7] != null) {
					widt = (String) objs[7];
				}

				if (objs[8] != null) {
					spec = (String) objs[8];
				}

				out.put("mtId", objs[0].toString());
				out.put("proId", objs[9].toString());
				out.put("mtName",
						EncCommonHelper.getSimpleObjectName(arg19,
								Long.parseLong(objs[0].toString())));
				out.put("proName", proName);
				out.put("requ", requ);
				out.put("unit", unit);
				out.put("pric", objs[4].toString());
				out.put("mark", mark);
				out.put("leng", leng);
				out.put("widt", widt);
				out.put("spec", spec);
				mapper.add(out);
			}

			map.put("items", mapper);
			map.put("status", "OK");
			map.put("errMsg", "");
		} catch (Exception arg18) {
			map.put("status", "ERROR");
			map.put("errMsg", arg18.toString());
		}

		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		ObjectMapper arg20 = new ObjectMapper();
		String arg21 = arg20.writeValueAsString(map);
		ServletOutputStream arg22 = response.getOutputStream();
		arg22.write(arg21.getBytes("utf-8"));
		arg22.flush();
		arg22.close();
		return null;
	}

	public ModelAndView handleGet(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String estType = request.getParameter("est_type");
		String priceType = request.getParameter("price_type");
		String estId = request.getParameter("est_id");
		String mtId = request.getParameter("mt_id");
		String proId = request.getParameter("pro_id");
		String proName = request.getParameter("pro_name");
		String getSta = request.getParameter("get_sta");
		HashMap map = new HashMap();

		String json;
		try {
			EstPrice mapper = this.estPriceDao.get(estType, priceType,
					Long.parseLong(estId), Long.parseLong(mtId),
					Long.parseLong(proId), proName);
			if (mapper == null && getSta != null && getSta.equals("Y")) {
				mapper = this.estPriceDao.get(estType, "STA", 0L,
						Long.parseLong(mtId), Long.parseLong(proId), proName);
			}

			json = "0";
			if (mapper != null) {
				json = mapper.getPrice().toString();
			}

			map.put("pric", json);
			map.put("status", "OK");
			map.put("errMsg", "");
		} catch (Exception arg13) {
			map.put("status", "ERROR");
			map.put("errMsg", arg13.toString());
		}

		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		ObjectMapper mapper1 = new ObjectMapper();
		json = mapper1.writeValueAsString(map);
		ServletOutputStream out = response.getOutputStream();
		out.write(json.getBytes("utf-8"));
		out.flush();
		out.close();
		return null;
	}

	public ModelAndView handleImpoForm(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView(this.impoFormView);
		mv.addObject("type", request.getParameter("type"));
		mv.addObject("estId", request.getParameter("est_id"));
		return mv;
	}

	public ModelAndView handleImpo(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String fileName = request.getParameter("file_name");
		String type = request.getParameter("type");
		String estId = request.getParameter("est_id");
		File file = new File(this.getServletContext().getRealPath(fileName));
		String alertMsg = "";
		BufferedInputStream in = null;

		try {
			in = new BufferedInputStream(new FileInputStream(file));
			HSSFWorkbook out = new HSSFWorkbook(new POIFSFileSystem(in));
			int count = 0;

			for (int str = 0; str < out.getNumberOfSheets(); ++str) {
				HSSFSheet hssfsheet = out.getSheetAt(str);

				for (int j = 1; j < hssfsheet.getPhysicalNumberOfRows(); ++j) {
					HSSFRow hssfrow = hssfsheet.getRow(j);
					if (hssfrow == null) {
						break;
					}

					boolean hasInput = false;
					HSSFCell cell = hssfrow.getCell(0);
					String mtName = PageHelper.getCellVal(cell, 0);
					hasInput = hasInput || !PageHelper.isEmpty(mtName);
					cell = hssfrow.getCell(1);
					String proName = PageHelper.getCellVal(cell, 100);
					hasInput = hasInput || !PageHelper.isEmpty(proName);
					cell = hssfrow.getCell(2);
					String widtStr = PageHelper.getCellVal(cell, 0);
					hasInput = hasInput || !PageHelper.isEmpty(widtStr);
					cell = hssfrow.getCell(3);
					String heigStr = PageHelper.getCellVal(cell, 0);
					hasInput = hasInput || !PageHelper.isEmpty(heigStr);
					cell = hssfrow.getCell(4);
					String spec = PageHelper.getCellVal(cell, 50);
					hasInput = hasInput || !PageHelper.isEmpty(spec);
					cell = hssfrow.getCell(5);
					String unit = PageHelper.getCellVal(cell, 15);
					hasInput = hasInput || !PageHelper.isEmpty(unit);
					cell = hssfrow.getCell(6);
					String upStr = PageHelper.getCellVal(cell, 0);
					hasInput = hasInput || !PageHelper.isEmpty(upStr);
					cell = hssfrow.getCell(7);
					String mr = PageHelper.getCellVal(cell, 100);
					hasInput = hasInput || !PageHelper.isEmpty(mr);
					cell = hssfrow.getCell(8);
					String mark = PageHelper.getCellVal(cell, 100);
					hasInput = hasInput || !PageHelper.isEmpty(mark);
					if (hasInput) {
						long mtId = 0L;
						long proId = 0L;
						boolean dataOk = true;
						if (dataOk && mtName != null && !mtName.equals("")) {
							MakeType up = this.makeTypeDao.getByName(mtName,
									true);
							if (up != null) {
								mtId = up.getId();
							}
						}

						if (mtId == 0L
								&& (proName == null || proName.equals(""))) {
							if (mtName != null && !mtName.equals("")) {
								alertMsg = PageHelper.appendAlertMsg(alertMsg,
										"第" + j + "行：找不到对应的项目类型！");
								dataOk = false;
							} else {
								alertMsg = PageHelper.appendAlertMsg(alertMsg,
										"第" + j + "行：项目类型和材质不能同时为空！");
								dataOk = false;
							}
						}

						if (dataOk && proName != null
								&& !proName.trim().equals("")) {
							Product arg50 = this.productDao.getByName(proName,
									true);
							if (arg50 != null) {
								proId = arg50.getId();
							}
						}

						if (dataOk && widtStr != null && !widtStr.equals("")) {
							try {
								new BigDecimal(widtStr);
							} catch (Exception arg45) {
								alertMsg = PageHelper.appendAlertMsg(alertMsg,
										"第" + j + "行：宽只能是数字！");
								dataOk = false;
							}
						}

						if (dataOk && heigStr != null && !heigStr.equals("")) {
							try {
								new BigDecimal(heigStr);
							} catch (Exception arg44) {
								alertMsg = PageHelper.appendAlertMsg(alertMsg,
										"第" + j + "行：高只能是数字！");
								dataOk = false;
							}
						}

						BigDecimal arg51 = new BigDecimal(0);
						if (dataOk) {
							if (upStr != null && !upStr.equals("")) {
								try {
									arg51 = (new BigDecimal(upStr)).setScale(4,
											4);
								} catch (Exception arg43) {
									alertMsg = PageHelper.appendAlertMsg(
											alertMsg, "第" + j + "行：单价只能是数字！");
									dataOk = false;
								}
							} else {
								alertMsg = PageHelper.appendAlertMsg(alertMsg,
										"第" + j + "行：单价不能为空！");
								dataOk = false;
							}
						}

						if (dataOk) {
							EstPrice ep = new EstPrice();
							if (type.equals("CLIE")) {
								ep.setEstType("CLIENT");
							} else {
								if (!type.equals("COOP")) {
									throw new Exception("type " + type
											+ " not supported!");
								}

								ep.setEstType("COOPERATOR");
							}

							ep.setId(this.idGenerator.getId(EstPrice.class
									.getName()));
							ep.setLength(heigStr);
							ep.setMakeRequire(mr);
							ep.setMakeTypeId(mtId);
							ep.setMark(mark);
							ep.setPrice(arg51);
							if (estId != null && !estId.equals("")) {
								ep.setPriceType("EST");
								ep.setEstId(Long.parseLong(estId));
							} else {
								ep.setPriceType("STA");
								ep.setEstId(0L);
							}

							ep.setProId(proId);
							ep.setProName(proName);
							ep.setProSpell(PageHelper
									.getPinYinHeadChar(proName).toUpperCase());
							ep.setSpecification(spec);
							ep.setUnit(unit);
							ep.setWidth(widtStr);
							this.estPriceDao.save(ep);
							++count;
						}
					}
				}
			}

			String arg49 = "<B>成功导入" + count + "行</B>";
			if (alertMsg != null && !alertMsg.equals("")) {
				alertMsg = PageHelper.appendAlertMsg(arg49, alertMsg);
			} else {
				alertMsg = arg49;
			}
		} catch (Exception arg46) {
			alertMsg = "导入错误：" + arg46.getMessage();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception arg42) {
				;
			}

		}

		EncCommonHelper.setAlertMessage(request, alertMsg);
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		ServletOutputStream arg48 = response.getOutputStream();
		arg48.write("OK".getBytes());
		arg48.flush();
		arg48.close();
		return null;
	}

	public String getListView() {
		return this.listView;
	}

	public void setListView(String listView) {
		this.listView = listView;
	}

	public EstPriceDao getEstPriceDao() {
		return this.estPriceDao;
	}

	public void setEstPriceDao(EstPriceDao estPriceDao) {
		this.estPriceDao = estPriceDao;
	}

	public String getListForSelectView() {
		return this.listForSelectView;
	}

	public void setListForSelectView(String listForSelectView) {
		this.listForSelectView = listForSelectView;
	}

	public MakeTypeDao getMakeTypeDao() {
		return this.makeTypeDao;
	}

	public void setMakeTypeDao(MakeTypeDao makeTypeDao) {
		this.makeTypeDao = makeTypeDao;
	}
}